package com.mark.web.common.service.Impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mark.common.Constant;
import com.mark.common.ServerResponse;
import com.mark.common.exception.Campuso2oException;
import com.mark.common.utils.OSSClientUtil;
import com.mark.common.utils.PathUtil;
import com.mark.common.utils.PropertiesUtil;
import com.mark.common.utils.UploadFileUtil;
import com.mark.web.common.service.IUploadFilesService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.security.auth.login.Configuration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 上传文件的service层接口实现
 * @Author: Kingsley
 * @CreateDate: 2018/10/5 13:49
 * @Version: 2.0
 * @Copyright : 豆浆油条个人非正式工作室
 */
@Service
public class UploadFilesServiceImpl implements IUploadFilesService {


    @Override
    public ServerResponse uploadFiles(MultipartFile[] files, String moduleName, String moduleId) {

        //根据模块获取存放各个模块的根路径
        String moduleBasePath;
        // TODO: 2019/6/2 策略模式
        if (StringUtils.equals(moduleName, "fragment")) {
            moduleBasePath = PathUtil.getFragmentPath(moduleId);
        } else if (StringUtils.equals(moduleName, "user")) {
            String fileBasePath = PathUtil.getImageBasePath();
            moduleBasePath = fileBasePath + PathUtil.getUserImageath(Long.parseLong(moduleId));
        } else {
            throw new Campuso2oException("上传文件暂不支持模块：" + moduleName);
        }

        //根据不同的上传文件方式上传文件
        List<Map<String, String>> resultList = Lists.newArrayList();
        if (Constant.CampusProperties.UPLOAD_FILE_TYPE.equals(1)) {
            for (MultipartFile multipartFile : files) {
                Map<String, String> urlMap = Maps.newHashMap();
                String url = UploadFileUtil.uploadFileToLocal(multipartFile, moduleBasePath);
                urlMap.put("url", url);
                resultList.add(urlMap);
            }
        }
        return ServerResponse.createBySuccess(resultList);
    }

    /*** 私有方法 ******************************************************/
    /**
     * 用户上传头像
     *
     * @param files：头像文件
     * @param role：用户身份
     * @param roleId：用户id
     * @return ：
     */
    private ServerResponse userUploadImages(MultipartFile[] files, String role, String roleId) {

        int userId = Integer.parseInt(roleId);

        //上传到OSS服务器
        String url = OSSClientUtil.uploadImg2Oss(files[0], role, userId);
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> resultMap = Maps.newHashMap();
        resultMap.put("url", url);
        resultList.add(resultMap);
        if (StringUtils.isNotBlank(url)) {
            return ServerResponse.createBySuccess(resultList);
        }
        return ServerResponse.createByErrorMessage("上传文件失败！");
    }
}
